package com.jdk.mode.relate;

import java.util.ArrayList;
import java.util.List;

/**
 * @author jukg
 * @date 2023/08/29 14:06
 * @description 迭代器模式  手撸简单迭代器，未考虑线程安全
 */
public class Aggregate {

    public static void main(String[] args) {
        Resteraunt1 r1 = new Resteraunt1();

        Resteraunt2 r2 = new Resteraunt2();

        Waitress w = new Waitress();
        w.register(r1.getIterator());
        w.register(r2.getIterator());
        w.printMenu();
    }
}

interface Iterator{

    boolean hasNext();

    Object next();

}

class MenuItem{
    private String name;

    private Integer price;

    public MenuItem(String name, Integer price) {
        this.name = name;
        this.price = price;
    }

    @Override
    public String toString() {
        return "MenuItem{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }
}



class Resteraunt1{

    private List<MenuItem> list = new ArrayList<>();

    int position;

    public Resteraunt1() {
        list.add(new MenuItem("中式1", 100));
        list.add(new MenuItem("中式2", 101));
        list.add(new MenuItem("中式3", 102));
        list.add(new MenuItem("中式4", 103));
        list.add(new MenuItem("中式5", 104));
    }

    public Iterator getIterator(){
        return new Iterator1();
    }

    class Iterator1 implements Iterator{

        @Override
        public boolean hasNext() {
            return position < list.size();
        }

        @Override
        public Object next() {
            if(position >= list.size()){
                return null;
            }
            MenuItem item = list.get(position);
            position ++;
            return item;
        }
    }
}

class Resteraunt2{

    private List<MenuItem> list = new ArrayList<>();

    int position;

    public Resteraunt2() {
        list.add(new MenuItem("法式1", 200));
        list.add(new MenuItem("法式2", 201));
        list.add(new MenuItem("法式3", 202));
        list.add(new MenuItem("法式4", 203));
        list.add(new MenuItem("法式5", 204));
    }
    public Iterator getIterator(){
        return new Iterator2();
    }

    class Iterator2 implements Iterator{

        @Override
        public boolean hasNext() {
            return position < list.size();
        }

        @Override
        public Object next() {
            if(position >= list.size()){
                return null;
            }
            MenuItem item = list.get(position);
            position ++;
            return item;
        }
    }
}

class Waitress{
    private List<Iterator> iterators = new ArrayList<>();

    public Waitress() {
    }

    public void register(Iterator iterator){
        iterators.add(iterator);
    }

    public void printMenu(){

        for(Iterator i: iterators){
             while (i.hasNext()){
                 System.out.println(i.next());
             }
        }
    }
}


